package br.org.universa.sgos.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import br.org.universa.sgos.entidade.Agente;
import br.org.universa.sgos.enums.OperacaoEnum;

@WebFilter(urlPatterns = "/*")
public class FiltroDeAuditoria implements Filter {

    private static final Logger logger = Logger.getLogger(FiltroDeAuditoria.class);

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;

        Agente usuario = (Agente) httpRequest.getSession().getAttribute("usuarioLogado");
        String loginUsuario = (usuario != null) ? usuario.getUsuario() : "<deslogado>";
        logger.info("Usuario: " + loginUsuario + ", URI: " + httpRequest.getRequestURI());

        String operacao = request.getParameter("operacao");

        logger.info("Usuario: " + usuario + ", Operacao : " + operacao);

        if (usuario == null && operacao != null && operacaoRestrita(operacao)) {

            logger.info("Request sem login! Redirecionando para a página de boas-vindas...");

            ((HttpServletResponse) response).sendRedirect("index.jsp");

        } else {

            chain.doFilter(request, response);

        }

    }

    private boolean operacaoRestrita(String operacao) {

        for (OperacaoEnum operacaoEnum : OperacaoEnum.values()) {
            if (operacaoEnum.getOperacao().equals(operacao)) {
                return operacaoEnum.isOperacaoRestrita();
            }
        }

        return false;
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

        BasicConfigurator.configure();

    }

}
